package com.wac.data.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wac.data.entity.Criticism;
import com.wac.data.entity.Criticism;
import com.wac.data.entity.Like;
import com.wac.data.mapper.CriticismMapper;
import com.wac.data.mapper.CriticismMapper;
import com.wac.data.mapper.LikeMapper;
import com.wac.data.service.CriticismService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wac.data.service.UserService;
import com.wac.data.utils.DataListUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author beta
 * @since 2023-03-16
 */
@Service
public class CriticismServiceImpl extends ServiceImpl<CriticismMapper, Criticism> implements CriticismService {

	@Resource
	private CriticismMapper criticismMapper;
	@Resource
	private UserService userService;
	@Resource
	private LikeMapper likeMapper;

	private Page<Criticism> thePage;


	@Override
	public Map<String, Object> selectByUserId(int page, String id) {
		thePage = new Page<>(page, 3);
		criticismMapper.selectPage(thePage, new QueryWrapper<Criticism>().eq("user_id", id).orderByDesc("time"));
		thePage.getRecords().forEach(
				criticism -> {
					criticism.setUser(userService.getUserSimpleInfo(criticism.getUserId()));
				}
		);
		return new DataListUtil().data(thePage);
	}

	@Override
	public Map<String, Object> selectByBangumiId(int page, String id, int order, String userId) {
		thePage = new Page<>(page, 5);
		if (order == 0) {
			criticismMapper.selectPage(thePage, new QueryWrapper<Criticism>().eq("bangumi_id", id).orderByAsc("time"));
		} else {
			criticismMapper.selectPage(thePage, new QueryWrapper<Criticism>().eq("bangumi_id", id).orderByDesc("time"));
		}
		thePage.getRecords().forEach(
				criticism -> {
					criticism.setUser(userService.getUserSimpleInfo(criticism.getUserId()));
					criticism.setLikeNum(likeMapper.getEntityLikeNum(criticism.getId()));
					if (userId != null) {
						criticism.setIsLike(likeMapper.selectOne(new QueryWrapper<Like>().eq("like_id", userId).eq("entity_id", criticism.getId())) != null ? 1 : 0);
					}
				}
		);

		return new DataListUtil().data(thePage);
	}

	@Override
	public int addCriticism(Criticism criticism) {
		return criticismMapper.insert(criticism);
	}

	@Override
	public int deleteCriticism(String id) {
		return criticismMapper.deleteById(id);
	}
}
